
import 'package:dio/dio.dart';
import 'package:trade/common/network/base/base_http.dart';
import 'package:trade/common/service/router_service/router_table.dart';
import 'package:trade/common/service/td_service.dart';

import 'base_http.dart';

abstract class BaseProtocol {

  num? code;
  String? msg;
  dynamic data;

  // bool get isSuccess => (null != data) && (false == (this.data is TDError));

  void parse(dynamic data) {

    if(this.data is TDError) {
      TDError e = this.data as TDError;
      onParseError(e);
      // if(e.hasErrResponse) {
      //   onParseErrorFromResponse(e.errResponse!);
      // }
    } else {
      var code = data['code'];
      if (code == null) {
        onParseError(TDError(errorCode: unknownErrorCode, errorMsg: unknownErrorMsg));
      } else if(code == 666){
        service.cache.clear();
        service.router.pushReplacementNamed(RouteName.loginPage);
      } else if (code != 2000) {
        var msg = data['msg'] ?? "未知错误";
        onParseError(TDError(errorCode: code, errorMsg:msg));
      } else {
        this.data = data['body'];
        onParse(this.data);
      }
    }
  }

  void onParse(dynamic data);

  void onParseError(TDError error) {
    this.code = error.errorCode;
    this.msg = error.errorMsg;

  }

  // void onParseErrorFromNetwork(Response errResponse) {
  //   /// 后台自定义的错误可以根据不同接口用errResponse.data单独解析
  //   ///
  //   /// 默认解析
  //   // this.code = errResponse.statusCode;
  //   // this.msg = '${this.code}: ${errResponse.data}';
  // }
  //
  // void onParseErrorFromServer(Response errResponse) {
  //
  // }

}
